package tech.eyao.hs60x.utils;

import java.security.Key;
import java.util.Date;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.joda.time.DateTime;
import org.omg.CORBA.PRIVATE_MEMBER;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import tech.eyao.hs60x.common.CommonConstants;

/**
 * 实现类
 * 
 * @author hejian
 * @date 2017年12月19日 下午3:22:38
 */
public class JwtHelper {
	private static final String base64Security = "Arr82342ERdu5sdEsas23s509D";

	public static Claims parseJWT(String jsonWebToken) {
		try {
			Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
					.parseClaimsJws(jsonWebToken).getBody();
			return claims;
		} catch (Exception ex) {
			return null;
		}
	}
	
	public static String createJWT(long userId, String deviceId, int day) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		String body = AesEcryptUtils.encode(AesEcryptUtils.RANDOM_KEY, userId + "|" + deviceId);
		// 生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		// 添加构成JWT的参数
		JwtBuilder builder = Jwts.builder()
				 .setHeaderParam(CommonConstants.JWT_TYPE_NAME, CommonConstants.JWT_TYPE_VALUE)
				 .setHeaderParam(CommonConstants.JWT_ALG_NAME, CommonConstants.JWT_ALG_VALUE)
				.claim(CommonConstants.TOKEN_BODY, body).signWith(signatureAlgorithm, signingKey);
		// 添加Token过期时间
		if (day >= 0) {
			Date exp = new DateTime().withTimeAtStartOfDay().plusDays(day).toDate();
			builder.setExpiration(exp).setNotBefore(now);
		}
		// 生成JWT
		return builder.compact();
	}
}
